wx.cloud.init({
  env: 'data-m4n9e'
})
const db = wx.cloud.database()
const req = db.collection('school-request')
const person = db.collection('person')
const news = db.collection('news')
const app = getApp()
var utils = require('../../utils/util.js')
Page({

  /**
   * 页面的初始数据
   */
  data: {
    imagesUrl:[],
    pageID:'',
    criticism:[],
    content:'',
    click:0,
    canIUse: wx.canIUse('button.open-type.getUserInfo'),
    touristID:'',
    creatorID:'',
    comments:'',
    figureID:[],
    imgnum:0,
    figureUrl:[],
    number:0,
    subComment:{},
    subCriticism:'',
    placeholder: '说说你的看法吧！(可以发至多三张图片)'
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    wx.showTabBarRedDot({
      index: 1,
    })
    var user = wx.getStorageSync('userInfo')
    if (!user.nickName && !user.avatarUrl) {
      this.setData({ authorize: true, signIn: false })
    }
    else {
      this.setData({ authorize: false, signIn: true })
    }
    wx.showLoading({
      title: '正努力加载数据',
    })
    this.data.pageID = options.id 
  // doc获取记录应用，options为包含页面参数的数组
    req.doc(options.id).get().then(res => {
      res.data.click += 1
      this.data.imagesUrl = res.data.imagesUrl
      this.data.openid = res.data._openid
      this.data.type = res.data.type
      this.data.touristID = options.openid
      this.data.subCriticism = res.data.subComment
      this.data.creatorID = res.data._openid
      this.data.description = res.data.description
      if(res.data.comment!=undefined){
        this.data.criticism = this.data.criticism.concat(res.data.comment)
      } 
      else{
        this.data.criticism =[]
      }
      wx.setStorageSync('criticism', this.data.criticism)
      if(res.data.user[2]==1){
        var gender ='/images/male.png'
      }
      else if (res.data.user[2] ==2){
        var gender ='/images/female.png'
      }
      this.setData({ 
        demand: res.data, 
        criticism: res.data.comment, 
        click: res.data.click, 
        gender: gender, 
        commentor: res.data.commentor, 
        creatorID: res.data._openid, 
        touristID: options.openid,
        order:false,
        index:true
        })
      wx.hideLoading()
      req.doc(this.data.pageID).update({
        data: {
          click: res.data.click,
        }
      })
    })
  },

  addimages: function (e) {
    // 因为在api内部，this对象的setData属性不被允许使用，所以就间接赋值给that方便传输文件路径至wxml的内部状态变量中。
    var that = this
    var img = new Array()
    var time = utils.formatTime(new Date())
    var openid = this.data.openid
    wx.chooseImage({
      count: 3,
      success: function(res){
        wx.showToast({
          title: '正努力加载图片',
          duration: 2000,
          mask: true,
          image: 'shenglvehao.png'
        })
        var tempFilePaths = res.tempFilePaths
        if(that.data.imgnum + tempFilePaths.length < 4){
          that.data.figureUrl = that.data.figureUrl.concat(tempFilePaths)
          // 用于计数
          var figurenum = new Array()
          figurenum = figurenum.concat(tempFilePaths)
          that.data.imgnum += figurenum.length
          that.setData({ figures: that.data.figureUrl })
          for (var num = -1; num < that.data.figureUrl.length;) {
            num++
            var name = time.substring(0, 5) + '/' + openid + '_' + num + '_' + Math.floor(Math.random() * 100)
            wx.cloud.uploadFile({
              cloudPath: `${name}.png`,
              filePath: that.data.figureUrl[num],
              success: res => {
                that.data.figureID.push(res.fileID)
              },
            })
          }
        }
        else {
          wx.showModal({
            title: '提示',
            content: '上传的图片数量不能超过3张哦',
          })
        } 
      }
    })
  },

  delimages: function (e) {
  // 增加调用deleteFile API节省存储空间
    this.data.figureID = []
    this.data.imgnum = 0
    this.data.figureUrl = []
    this.setData({ figureID: [],figures:[] })
    wx.cloud.deleteFile({
      fileList: this.data.figureID
    })
  },

// placeholder没有z-index属性，只好另外写两个函数自制placeholder
  focusText(){
    this.setData({placeholder:''})
  },

  blurText(e){
    if (!e.detail.value){
      this.setData({ placeholder: '说说你的看法吧！(可以发至多三张图片)' })
    } 
  },

  previewImages: function (e) {
    wx.previewImage({
      current: e.currentTarget.dataset.imageurl,
      urls: this.data.imagesUrl,
    })
  },

  previewCommentImages: function (e) {
    var index = e.currentTarget.dataset.index   
    wx.previewImage({
      current: e.currentTarget.dataset.figure,
      urls: this.data.criticism[index][5],
    })
  },

  makeComment:function(){
    var that = this
    // createSelectorQuery()获取'.comment'选择器上边坐标，以获取容器高度
    wx.createSelectorQuery().select('.comment').boundingClientRect(function (rect) {
      // 使页面滚动到底部
      wx.pageScrollTo({
        scrollTop: rect.bottom,
        success:function(){
          that.setData({ focus: true })
        }
      })
    }).exec()
  },

  remarkOn:function(e){
    var openid = e.currentTarget.dataset.openid
    var index = e.currentTarget.dataset.index
    var comment = wx.getStorageSync('criticism')
    if (openid == comment[index][4]){
      wx.showToast({
        title: '只能点赞别人哦',
        image:'/images/close-circle.png'
      })
    }
    else{
      wx.showToast({
        title: '点赞成功！',
      })
      comment[index][7] += 1
    // 直接使用setData更新wx:for绑定的数据就能实时更新点赞量了
      this.setData({ criticism: comment})
      wx.setStorageSync('criticism', comment)
      this.data.theRemark =  true
    }
  },

  subRemarkOn: function (e) {
    var subindex = e.currentTarget.dataset.subindex
    var openid = e.currentTarget.dataset.openid
    var index = e.currentTarget.dataset.index
    var comment = wx.getStorageSync('criticism')
    if (openid == comment[index][6][subindex][4]){
      wx.showToast({
        title: '只能点赞别人哦',
        image: '/images/close-circle.png'
      })
      
    }
    else{
      wx.showToast({
        title: '点赞成功！',
      })
      comment[index][6][subindex][5] ++ 
      this.setData({criticism: comment})
      wx.setStorageSync('criticism', comment)
      this.data.theRemark = true
    }
  },

// 用户离开本页面后，再调用云函数将评论数据写入数据库，节省资源
  onUnload: function () {
    var comment = wx.getStorageSync('criticism')
    // 只有删除评论、没有点赞和添加评论的操作
    if(!this.data.theRefer){
      wx.cloud.callFunction({
        name: 'comments',
        data: {
          comment: comment,
          pageID: this.data.pageID,
          refer: false
        }
      })
      wx.removeStorageSync('')
    }

    else if(this.data.theDelete || this.data.theRemark || this.data.theRefer){
      wx.cloud.callFunction({
        name: 'comments',
        data: {
          comment: comment,
          pageID: this.data.pageID,
          refer: true
        }
      })
    }
  },

  actionSheet(e){
  // 查看用户点击第几个
    var index = e.currentTarget.dataset.index   
    this.data.index= index
    wx.showActionSheet({
      itemList: ['举报'],
      success:res=>{
        if(res.tapIndex==0){
          var url = '/pages/report/report?id=' + this.data.pageID + '&type=评论' + '&tourist=' + this.data.touristID + '&creator=' + this.data.criticism[index][4] + '&content=' + this.data.criticism[index][3]
          wx.navigateTo({
            url: url,
          })
        }
      }
    })
  },

  commentOf:function(e){
    this.data.index = e.currentTarget.dataset.index   
    this.setData({ subfocus: true, suborder: this.data.index })
  },

  subActionSheet(e){
    var index = e.currentTarget.dataset.index
    var subindex = e.currentTarget.dataset.subindex
    wx.showActionSheet({
      itemList: ['举报'],
      success:res=>{
        if(res.tapIndex==0){
          var url = '/pages/report/report?id=' + this.data.pageID + '&type=评论' + '&tourist=' + this.data.touristID + '&creator=' + this.data.criticism[index][6][subindex][4] + '&content=' + this.data.criticism[index][6][subindex][3]
          wx.navigateTo({
            url: url,
          })
        }
      }
    })
  },

  delectMessage:function(){
    wx.showModal({
      title: '提醒！',
      content: '是否确定删除这条已发布的消息（包含下方评论）',
      success: res=>{
        if (res.confirm) {

          wx.showLoading({
            title: '正在删除数据',
          })
          wx.cloud.deleteFile({
            fileList: this.data.imagesUrl
          })
          wx.cloud.callFunction({
            name:'delectData',
            data:{
              id: this.data.pageID
            },
            complete:res=>{
              wx.reLaunch({
                url: '/pages/index/index'
              })
              wx.hideLoading()
            }
          })
        }
      }
    })
  },

  delectComment:function(result,type){
    wx.showModal({
      title: '提示',
      content: '确定要删除已发布的评论吗(包含下方评论)？',
      success:res=>{
        this.data.theDelete = true
        if (res.confirm){
          wx.showLoading({
            title: '正在删除评论',
          })     
          // 循环去除空值
          for (var i = 0; i < result.length; i++) {
            if (result[i] == "") {
              result.splice(i, 1);
              i--
            }
          }
          if(type=='comment'){
            this.setData({ criticism: result, order: false })
            wx.setStorageSync('criticism', result)
            wx.hideLoading()
          }
          else if(type=='subComment'){
            this.setData({ subCriticism: result, criticism: this.data.criticism })
            wx.setStorageSync('criticism', this.data.criticism)
            wx.hideLoading()
          }
        }
      }
    })
  }, 

  delectSubComment:function(e){
    // data自定义属性，在渲染层有大小写但到了逻辑层又会变成全部小写。
    var subindex = e.currentTarget.dataset.subindex
    var index = e.currentTarget.dataset.index
    this.data.criticism[index][6].splice(subindex,1)
    this.delectComment(this.data.criticism[index][6],'subComment')
    var acceptor = this.data.criticism[index][4]
    var writer = this.data.touristID
  },

  delectParComment:function(e){
    var index = e.currentTarget.dataset.index  
    var delect = this.data.criticism.splice(index, 1) 
    wx.cloud.deleteFile({
      fileList:delect[5]
    })
    this.delectComment(this.data.criticism, 'comment')
  },

  getuserinfo(res) {
    if (res.detail.userInfo) {
      wx.setStorageSync('userInfo', res.detail.userInfo)
      this.setData({ authorize: false, signIn: true })
      var user = res.detail.userInfo
      person.add({
        data: {
          name: user.nickName,
          avatarImage: user.avatarUrl,
          gender: user.gender
        }
      })
    } 
  },

  toReport(){
    var url = '/pages/report/report?id=' + this.data.pageID + '&type=消息' + '&tourist=' + this.data.touristID + '&creator=' + this.data.creatorID + '&content=' + this.data.description
    wx.navigateTo({
      url: url,
    })
  },


// 提交评论的父级函数
// 发送模板消息的功能，form_id只能发送给操作者本人，无法发给别人，所以不考虑调用templateInfo云函数了
  refer:function(result,commentType){
    wx.showLoading({
      title: '正在发送……',
    })
    if (result.length == 2) {
      for (var i = 0; i < result.length; i++) {
        if (result[i] == "") {
          result.splice(i, 1);
          i--
        }
      }
    }
    if (commentType == 'comment') {
      this.setData({ criticism: result, content: '', order: false })
      wx.setStorageSync('criticism', result)
    }
    else if (commentType == 'subComment') {
      this.setData({ subCriticism: result, subcontent: '', suborder: this.data.index, criticism: result, subfocus: false })
      wx.setStorageSync('criticism', result)
    }
    wx.hideLoading()
    wx.showToast({
      title: '发送成功！',
    })
    this.data.theRefer= true
  },

  referSubComment: function (e) {    
    // index父级评论索引异常导致子评论功能无法正常使用
    var index = this.data.index
    var userInfo = wx.getStorageSync('userInfo')
    var commentCreatTime = utils.formatTime(new Date())
    // 最后一个元素用于储存点赞量
    var result = [userInfo.nickName, userInfo.avatarUrl, commentCreatTime, e.detail.value.subcomment, this.data.touristID, 0]
    // 文本内容安全检查
    var content = e.detail.value.subcomment
    if(content!=''){
      wx.showLoading({
        title: '正在发送中……',
      })
      wx.request({
        url: 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wx5f250d9fbc13524d&secret=46d719bd09ae4a8895b66b9f4ce269c3',
        success: res => {
          var token = res.data.access_token
          var url = 'https://api.weixin.qq.com/wxa/msg_sec_check?access_token=' + token
          wx.request({
            url: url,
            method: 'POST',
            data: {
              content: content
            },
            success: res => {
              wx.hideLoading()
              if (res.data.errcode == 87014) {
                wx.showModal({
                  title: '警告!',
                  content: '你创建的消息中含有违法违规内容，请修改好后再提交。',
                  showCancel: false
                })
              }
              else{
                var date = new Date(commentCreatTime)
                var comment = wx.getStorageSync('criticism')
                comment[index][6].push(result)
                // risky 判断内容是否违规
                if (result[3] != '') {
                  this.refer(comment, 'subComment')
                  news.add({
                    data: {
                      acceptor: comment[index][4],
                      writer: [userInfo.nickName, userInfo.avatarUrl, this.data.touristID],
                      content: [e.detail.value.subcomment],
                      time: commentCreatTime,
                      url: `/pages/details/details?id=${this.data.pageID}`,
                      essayType: this.data.type,
                      detailsPageID: this.data.pageID,
                      refer: true,
                      date: date
                    },
                  })
                }
              }
            },
            fail: res => {
              wx.showToast({
                title: '服务器忙请稍后',
              })
            }
          })
        },
        fail: res => {
          wx.hideLoading()
          if (res.data.errcode == -1) {
            wx.showToast({
              title: '服务器忙请稍后',
            })
          }
        }
      })
    }
    else{
      wx.showToast({
        title: '你还没创建内容',
        image: 'close-circle.png'
      })
    }
  },

  referComment: function (e){ 
    // 只能用缓存来传评论数据
    var criticism = wx.getStorageSync('criticism')
    var userInfo = wx.getStorageSync('userInfo')
    var commentCreatTime = utils.formatTime(new Date())
    var images = this.data.figureID
    // 第六个元素用于储存子级评论，最后一个用于储存点赞量
    var result = [userInfo.nickName, userInfo.avatarUrl, commentCreatTime, e.detail.value.comment, this.data.touristID, images, [],0]
    // 增加内容安全审核
    var content = e.detail.value.comment
    if(content==''){
      wx.showToast({
        title: '你还没创建内容',
        image: 'close-circle.png'
      })
    }
    else{
      wx.showLoading({
        title: '正在发送中……',
      })
      wx.request({
        url: 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid=wx5f250d9fbc13524d&secret=46d719bd09ae4a8895b66b9f4ce269c3',
        success: res => {
          var token = res.data.access_token
          var url = 'https://api.weixin.qq.com/wxa/msg_sec_check?access_token=' + token
          wx.request({
            url: url,
            method: 'POST',
            data: {
              content: content
            },
            success: res => {
              wx.hideLoading()
              if (res.data.errcode == 87014) {
                wx.showModal({
                  title: '警告!',
                  content: '你创建的消息中含有违法违规内容，请修改好后再提交。',
                  showCancel: false
                })
              }
              else{
                criticism.push(result)
                if (result[3]) {
                  this.refer(criticism, 'comment')
                  this.data.figureID = []
                  this.data.imgnum = 0
                  this.data.figureUrl = []
                  this.setData({ figureID: [], figures: [] })
                }
              }
            },
            fail: res => {
              wx.hideLoading()
              wx.showToast({
                title: '服务器忙请稍后',
              })
            }
          })
        },
        fail: res => {
          if (res.data.errcode == -1) {
            wx.showToast({
              title: '服务器忙请稍后',
            })
          }
        }
      })
    } 
  },

  onShareAppMessage: function () {
    return {
      title:'南苑圈子，方便你我',
      path:`pages/details/details?id=${this.data.pageID}`,
      imageUrl: "cloud://data-m4n9e.6461-data-m4n9e-1300093224/project_images/logo.jpg"
    }
  },

})